package com.bjpowernode.shop.controller;

import com.bjpowernode.shop.base.BaseVo;
import com.bjpowernode.shop.domain.PayVo;
import com.bjpowernode.shop.feign.OrderServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/p/order")
public class PayController extends BaseVo {
    
    @Autowired
    private OrderServiceFeign orderServiceFeign;

    // 前端提交订单，发送pay请求，后端接受请求返回支付地址，前端将地址转换为QrCode
    @PostMapping("/pay")
    public ResponseEntity<String> getQcode(@RequestBody PayVo payVo) {
        // 调用service，在service中调用支付宝支付操作
        // 返回支付地址，前端根据该页面地址，加载成二维码显示
       return ResponseEntity.ok(payVoService.trade(payVo));
    }

    // 用户进行支付操作后，支付宝回调，后端在回调中判断支付状态，支付成功则修改数据库
    @PostMapping("/aliPayNotify")
    public void aliPayNotify(@RequestParam Map<String,Object> params){
        System.out.println("params = " + params);
        
        // 获取支付结果
        String tradeStatus = String.valueOf(params.get("trade_status"));
        if (tradeStatus.equals("TRADE_SUCCESS")){
            // 支付成功则获取支付的商家订单号
            String outTradeNo = (String) params.get("out_trade_no");
            // 根据订单号更新支付状态
            orderServiceFeign.updateIsPay(outTradeNo);
        }
    }
}
